// 导入用户集合
const { User } = require('../../../model/user');
const { generateToken } =  require('../../../middleGuard/jwt.js')

module.exports = async (req, res) => {
  const body = req.body
  const { username, signature, userInfo } = req.body
  console.log('body', body)
  const query = {}
  if(signature) query.wxSignature = signature
  if(username) query.username = username
  const user = await User.findOne(query)
  if (!user) {
    // 用户不存在
    if(signature) {
      // 微信登录，自动注册
      User.create({
        wxSignature: signature,
        avatar: userInfo.avatarUrl,
        nickname: userInfo.nickName
      }).then(item => {
        console.log('item', item)
        res.json({
            data: {
              ...item.toObject(),
              token: generateToken({userId: item._id})
            },
            message: '创建用户成功！'
        })
      }).catch((err) => {
        res.status(403)
        res.json({
            log: err,
            message: '用户创建失败！' + err
        })
      })
    } else {
      // 用户名登录
      res.status(403)
      res.json({
          message: '用户不存在！'
      })
    }
  } else {
      if(user.password === body.password) {
        if (user.state !== 0) {
            const { _id, username, nickname, avatar, roleType } = user
            const data = {
              _id,
              nickname,
              avatar, 
              roleType,
              username
            }
            const token = generateToken({userId: _id})
            data.token = token
          res.json({
              data,
              message: '登录成功！'
          })
        } else {
          res.status(403)
          res.json({
              message: '用户已被冻结！'
          })
        }
      } else {
          res.status(403)
          res.json({
              message: '密码错误！'
          })
      }
  }
  console.log(user)
}